package com.example.zzx.dovebook.bookshare.booksharehome;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.example.baselibrary.commonutil.FormatUtil;
import com.example.baselibrary.commonutil.ToastUtil;
import com.example.baselibrary.net.HttpUtil;
import com.example.baselibrary.widget.InterceptRelativeLayout;
import com.example.baselibrary.widget.LoadingDialog;
import com.example.baselibrary.widget.LoadingStateView;
import com.example.library.BaseAdapter;
import com.example.zzx.dovebook.R;
import com.example.zzx.dovebook.base.BaseActivity;
import com.example.zzx.dovebook.base.model.BookShare;
import com.example.zzx.dovebook.bookshare.booksharehome.model.Comment;
import com.example.zzx.dovebook.bookshare.booksharehome.model.CommentReply;
import com.example.zzx.dovebook.bookshare.booksharehome.model.HomeBookShare;
import com.example.zzx.dovebook.booktrace.BookTraceActivity;
import com.example.zzx.dovebook.login.LoginCheck;
import com.example.zzx.dovebook.message.MessageActivity;
import com.example.zzx.dovebook.user.UserManager;
import com.example.zzx.dovebook.utils.AnimationUtil;
import com.example.zzx.dovebook.utils.LocationUtil;
import com.example.zzx.heartanimation.LikeLayout;

import java.util.List;

import static com.example.zzx.dovebook.base.ValueWrapper.*;

/**
 * 历史遗留 UI 改变后理应叫做BookShareDetail，
 * create by zzx
 * create at 19-4-18
 */
public class BookShareHomeActivity extends BaseActivity<BookShareHomeViewModel> {


    @BindView(R.id.book_share_home_root_view)
    InterceptRelativeLayout rootView;
    @BindView(R.id.book_share_home_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.book_share_home_mask_view)
    View maskView;
    @BindView(R.id.book_share_home_bottom_add_layout)
    RelativeLayout addLayout;

    private UploadDialog mUploadDialog;
    private CommentDialog mCommentDialog;

    private BaseAdapter mAdapter;

    private LoadingStateView mEmptyView;

    private LoadingDialog mLoadingDialog;

    private long mLastCreateAt;

    private String[] mBookShareTips = new String[] {
            "图书分享需要一张图片",
            "木有书名",
            "木有作者",
            "请输入13位isbn号",
            "请输入分享理由"
    };

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setupUploadDialog();

        setupCommentDialog();

        setupRecyclerView();

        setupRootView();

        setupAddLayout();

        mLoadingDialog = new LoadingDialog(this);
    }

    private void setupCommentDialog() {
        mCommentDialog = new CommentDialog(this);
    }


    public void showUploadDialog() {
        mUploadDialog.show();
    }

    public void showCommentDialog(BookShare bookShare) {
        if (mCommentDialog == null) {
            mCommentDialog = new CommentDialog(this);
        }
        mCommentDialog.show(bookShare);
    }

    @Override
    protected int getStatusBarColor() {
        return STATUS_BAR_TRANSPARENT;
    }

    @Override
    protected void initOptions(Bundle savedInstanceState) {
        recyclerView.post(() -> startLocation());

        queryHotBookShare();
    }

    private void startLocation() {
        if (UserManager.getInstance(this).hasLocationInfo()) {
            return;
        }
        LocationUtil.INSTANCE.location(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                UserManager.getInstance(BookShareHomeActivity.this)
                        .saveLocation(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            }
        });
    }

    private void queryHotBookShare() {
        if (mLastCreateAt == 0L) {
            mLastCreateAt = System.currentTimeMillis();
        }
        if (mAdapter.getDataCount() > 0) {
            mLastCreateAt = ((HomeBookShare) mAdapter.getLastItem()).bookShare.getCreateAt();
        }
        String userId = UserManager.getInstance(this).getLoginUserId();
        userId = userId == null ? "" : userId;
        getViewModel().queryHotBookShare(userId, mLastCreateAt).observe(this, wrapper -> {
            if (wrapper.value == null) {
                if (mAdapter.getDataCount() > 0) {
//                    mLoadMoreView.noMore();
                } else {
                    if (wrapper.type == TYPE_FAILED) {
                        mEmptyView.failed();
                    } else if (wrapper.type == TYPE_NO_CONTENT) {
                        mEmptyView.empty();
                    }
                }
                return;
            }
            List<HomeBookShare> bookShareList = (List<HomeBookShare>) wrapper.value;
            if (mAdapter.isInEmptyState()) {
                mAdapter.cancelEmptyState();
            }
            if (bookShareList.size() < 10) {
                mAdapter.add(bookShareList);
//                mLoadMoreView.noMore();
            } else {
                mAdapter.add(bookShareList);
            }
        });
    }

    @OnClick(R.id.book_share_home_navigator)
    @LoginCheck
    public void navigatorToPersonalActivity() {
//        startActivity(new Intent(this, PersonalCenterActivity.class));
    }

    @OnClick(R.id.book_share_home_remind)
    @LoginCheck
    public void navigatorToMessageActivity() {
        startActivity(new Intent(this, MessageActivity.class));
    }

    @LoginCheck
    public void bookShareLike(BookShare bookShare, LikeLayout likeLayout) {
        getViewModel().bookShareLike(bookShare.getBookShareId(), UserManager.getInstance(this).getLoginUserId())
                .observe(this, success -> {
                    if (success) {
                        bookShare.setLikeCount(bookShare.getLikeCount() + 1);
                        bookShare.setHasLike(true);
                        likeLayout.toggle(FormatUtil.countFormat(bookShare.getLikeCount()));
                    }
                });
    }

    @LoginCheck
    public void cancelBookShareLike(BookShare bookShare, LikeLayout likeLayout) {
        getViewModel().cancelBookShareLike(bookShare.getBookShareId(), UserManager.getInstance(this).getLoginUserId())
                .observe(this, success -> {
                    if (success) {
                        bookShare.setLikeCount(bookShare.getLikeCount() - 1);
                        bookShare.setHasLike(false);
                        likeLayout.toggle(FormatUtil.countFormat(bookShare.getLikeCount()));
                    }
                });
    }

    /**
     * 查询用户方式为图书传递的分享(非第一个分享此图书的用户)
     */
//    private void queryPassedBookShare() {
//        getViewModel()
//                .queryPassedBookShare(UserManager.getInstance(this).getLoginUserId())
//                .observe(this, (bookShareList) -> {
//                    mAdapter.add(bookShareList);
//                });
//    }
    public void queryComments(String bookShareId, long date) {
        getViewModel().queryComments(UserManager.getInstance(this).getLoginUserId(), bookShareId, date)
                .observe(this, wrapper -> {
                    mCommentDialog.addCommentToRecycler(wrapper);
                });

    }


    @Override
    protected Object createRepository() {
        return new BookShareHomeRepository();
    }

    private void setupAddLayout() {
        addLayout.setOnClickListener((v) -> {
            showUploadDialog();
        });
    }

    private void setMaskViewAlpha(float percent) {
        percent = percent > 0.5f ? 0.5f : percent;
        maskView.setAlpha(percent);
    }

    private void setupRootView() {
        rootView.setOnScrollListener(new InterceptRelativeLayout.OnScrollListener() {
            @Override
            public boolean onScroll(VelocityTracker velocityTracker, int dx, int dy) {
                if (maskView.getVisibility() == View.GONE) {
                    maskView.setVisibility(View.VISIBLE);
                }
                setMaskViewAlpha(dy > 0 ? (float) dy / 800f : 0.07f);
                return true;
            }

            @Override
            public boolean onScrollFinish(VelocityTracker velocityTracker, int dx, int dy) {
                maskView.animate().alpha((float) 0x11 / 0xFF).setDuration(300).start();
                float yVT = velocityTracker.getYVelocity();
                if (-yVT >= 500) {
                    mUploadDialog.show();
                }
                return true;
            }
        });
    }

    private void setupRecyclerView() {
        mEmptyView = new LoadingStateView(this);
        mAdapter = new BaseAdapter.Builder().emptyView(mEmptyView).build();
        recyclerView.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL, false));
        new PagerSnapHelper().attachToRecyclerView(recyclerView);
        recyclerView.setAdapter(mAdapter);
    }

    private void setupUploadDialog() {
        mUploadDialog = new UploadDialog(this);
//        mUploadDialog.setContentView(R.layout.upload_dialog);
//        mUploadDialog.getDelegate().findViewById(android.support.design.R.id.container)
//                .setFitsSystemWindows(false);
//        mUploadDialog.getDelegate().findViewById(android.support.design.R.id.coordinator)
//                .setFitsSystemWindows(false);
//        mUploadDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
//                .setBackgroundResource(R.drawable.top_corner);

    }

    /**
     * 上传分享
     *
     * @param coverPath   封面地址
     * @param bookName    书籍名称
     * @param bookAuthor  作者
     * @param bookIsbn    书籍isbn
     * @param description 分享理由
     */
    public void uploadBookShare(String coverPath, String bookName, String bookAuthor, String bookIsbn,
                                String description, LatLonPoint latLonPoint) {
        String[] paramValues = new String[] {coverPath, bookName, bookAuthor, bookIsbn, description};
        String errorMessage = HttpUtil.checkParams(mBookShareTips, paramValues);
        if (!TextUtils.isEmpty(errorMessage)) {
            ToastUtil.shortToast(this, errorMessage);
            return;
        }
        mLoadingDialog.show();
        getViewModel().uploadBookShare(coverPath, bookName, bookAuthor, bookIsbn,
                UserManager.getInstance(this).getLoginUserId(), description, latLonPoint)
                .observe(this, (data) -> {
                    if (data.type == TYPE_NORMAL) {
                        ToastUtil.shortToast(this, "上传成功");
                    }
                    mLoadingDialog.dismiss();
                    mUploadDialog.dismiss();
                });
    }

    public void addComment(@Nullable Comment comment) {
        comment.setFromUserId(UserManager.getInstance(this).getLoginUserId());
        getViewModel().addComment(comment).observe(this, (commentResult) -> {
            mCommentDialog.addCommentToRecycler(commentResult);
        });
    }

    public void replyComment(Comment commentReply, String toUserName) {
        getViewModel().replyComment(commentReply).observe(this, (reply) -> {
            reply.setReplyToUserName(toUserName);
            reply.setReplyFromUserName(UserManager.getInstance(this).getLoginUserName());
            mCommentDialog.addReplyToRecycler(reply);
        });
    }

    public void showReplyEdit(CommentReply reply, Comment replyParentComment) {
        mCommentDialog.showReplyEdit(reply, replyParentComment);
    }

    public void showReplyEdit(Comment comment) {
        mCommentDialog.showReplyEdit(comment);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_book_share_home;
    }

    @Override
    protected Class<BookShareHomeViewModel> createViewModel() {
        return BookShareHomeViewModel.class;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case UploadDialog.PICTURE_WAY_ALBUM:
            case UploadDialog.PICTURE_WAY_TAKE:
            case UploadDialog.REQUEST_CODE_LOCATION:
                mUploadDialog.onActivityResult(requestCode, resultCode, data);
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == UploadDialog.PICTURE_ALBUM_PERMISSION
//                || requestCode == UploadDialog.PICTURE_TAKE_PERMISSION) {
//            mUploadDialog.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCommentDialog.isShowing()) {
            mCommentDialog.dismiss();
        }
        mCommentDialog = null;
        if (mUploadDialog.isShowing()) {
            mUploadDialog.dismiss();
        }
        mUploadDialog = null;
    }

    @LoginCheck
    public void startBookTraceActivity(String bookId, int bookStatus) {
        Intent intent = new Intent(this, BookTraceActivity.class);
        intent.putExtra("book_id", bookId);
        intent.putExtra("book_status", bookStatus);
        startActivity(intent);
    }

    @LoginCheck
    public void follow(BookShare bookShare, final TextView followTv) {
        String requestUserId = UserManager.getInstance(this).getLoginUserId();
        if (requestUserId == null) {
            return;
        }
        getViewModel().follow(requestUserId, bookShare.getUserId()).observe(this, (followState) -> {
            AnimationUtil.hide(followTv);
        });
    }
}
